package com.springboot.cloud.common.core.util;

import lombok.Data;
import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZengJian on 2021/2/3 0003 上午 9:22
 */
@Data
public class TreeNodeForVueUtile<T> {
    private String label;
    private String id;
    private String parentId;
    private T t;

    private List<TreeNodeForVueUtile> children;

    public TreeNodeForVueUtile() {
    }


    public TreeNodeForVueUtile(T t, String label, String id, String parentId) {
        this.t = t;

        this.label = label;
        this.id = id;
        this.parentId = parentId;
    }

    public TreeNodeForVueUtile(String label, String id, String parentId) {
        this.label = label;
        this.id = id;
        this.parentId = parentId;
    }


    /**
     * 递归（先得到父节点）再递归
     *
     * @param list
     * @return
     */
    public static List<TreeNodeForVueUtile> getTreeResult(List<TreeNodeForVueUtile> list) {
        List<TreeNodeForVueUtile> listResult = new ArrayList<>();
        for (com.springboot.cloud.common.core.util.TreeNodeForVueUtile t : list) {
            if (t.getParentId().equals("-1")) {
                listResult.add(t);// 得到父类
            }
        }
        secondTree(list, listResult);
        return listResult;
    }

    /**
     * 父节点获取子节点
     *
     * @param list
     * @param listResult
     * @return
     */

    public static void secondTree(List<TreeNodeForVueUtile> list, List<TreeNodeForVueUtile> listResult) {
        for (com.springboot.cloud.common.core.util.TreeNodeForVueUtile tResult : listResult) {
            List<TreeNodeForVueUtile> childrens = new ArrayList<>();
            for (com.springboot.cloud.common.core.util.TreeNodeForVueUtile t : list) {
                if (t.getParentId().equals("-1")) {
                    continue;
                }
                if (tResult.getId().equals(t.getParentId())) {
                    childrens.add(t);
                }
            }
            tResult.setChildren(childrens);
            if (!tResult.getChildren().isEmpty()) {
                secondTree(list, tResult.getChildren());
            }
        }

    }

    //使用方法参考
  /*  List< TreeNodeForVueUtile> tree = new ArrayList<>();
        for (EventType e:list //原来的数据进行转换，list是原来的数据
                ) {
        tree.add(new TreeNodeForVueUtile(e.getName(), e.getEventTypeId(), e.getParentId()));
    }
    List<TreeNodeForVueUtile> result =  TreeNodeForVueUtile.getTreeResult(tree);     //递归得到的结果
    */
}
